﻿using J.Model;
using J.ProductGet.Application.Command.ProductCommand;
using MediatR;
using Microsoft.IdentityModel.Tokens;
using ProductDto;
using SqlSugar;
using StatusDto;
using System.Drawing.Printing;

namespace J.ProductGet.Application.CommandHandler.ProductCommandHandler
{
    public class ProductGetCommandHandler : IRequestHandler<ProductGetCommand, PageDto<CommodityClassificationDto>>
    {
        private readonly ISqlSugarClient _sqlSugarClient;
        public ProductGetCommandHandler(ISqlSugarClient sqlSugarClient)
        {
            _sqlSugarClient = sqlSugarClient;
        }
        public async Task<PageDto<CommodityClassificationDto>> Handle(ProductGetCommand request, CancellationToken cancellationToken)
        {
           
            var oneClass = _sqlSugarClient.Queryable<Product>().LeftJoin<ClassifiedManagement>((x, y) => (x.CategoryManagementID == y.CategoryManagementID)).OrderByDescending(x => x.ProductID);

            if (!string.IsNullOrEmpty(request.ProductName))
            {
                oneClass = oneClass.Where(x => x.ProductName.Contains(request.ProductName));
            }
            if (!string.IsNullOrEmpty(Convert.ToString(request.CommodityStatus)) )
            {
                oneClass = oneClass.Where(x => x.CommodityStatus == request.CommodityStatus);
            }

            int PageTotal = oneClass.Count();
            int PageCount = (int)Math.Ceiling(PageTotal * 1.0 / request.pageSize);


            var query = await oneClass.Select((x, y) => new CommodityClassificationDto()
            {
                productId = x.ProductID,
                ProductName = x.ProductName,
                SellingPrice = x.SellingPrice,
                ClassificationName = x.CommodityType,
                SurplusStock = x.SurplusStock,
                sort = x.ProductID,
                CommodityStatus = x.CommodityStatus,
            }).Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToListAsync();

            return new PageDto<CommodityClassificationDto>
            {
                Data = query,
                pagedCount = PageCount,
                pageIndex = request.pageIndex,
                pageSize = request.pageSize,
                totalCount = PageTotal
            };
        }
    }
}
